package juc.work;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 可重入锁交替打印ABC
 */
public class PrintABCRelock {
    public static void main(String[] args) {
        AwaitSingal awaitSingal = new AwaitSingal(100);
        Condition conditionA = awaitSingal.newCondition();
        Condition conditionB = awaitSingal.newCondition();
        Condition conditionC = awaitSingal.newCondition();
        Thread threadA = new Thread(() -> awaitSingal.print("a", conditionA, conditionB));
        Thread threadB = new Thread(() -> awaitSingal.print("b", conditionB, conditionC));
        Thread threadC = new Thread(() -> awaitSingal.print("c", conditionC, conditionA));
        threadA.start();
        threadB.start();
        threadC.start();
        // 注意要获取awaitSingal的锁才能await
        System.out.println("开始");
        awaitSingal.lock();
        try {
            conditionA.signal();
        } finally {
            awaitSingal.unlock();
        }
    }
}

class AwaitSingal extends ReentrantLock {
    private int cnt = 0;
    public AwaitSingal(int cnt) {
        this.cnt = cnt;
    }

    public void print(String str, Condition current, Condition next) {
        for (int i = 0; i < cnt; i++) {
            lock();
            try {
                current.await();
                System.out.println(str);
                next.signal();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                unlock();
            }
        }
    }
}
